/**
 * @(#)JdbcTemplate.java 2014-4-22
 *
 * Copyright (c) 2012-2014 www.52weixue.com.
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information of 52weixue.com.
 * You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into with 52weixue.com.
 *
 * Distributable under GNU LGPL license by gnu.org
 */

package pers.lt.jdbc;

import org.hibernate.*;
import org.hibernate.transform.Transformers;
import org.springframework.dao.DataAccessException;
import pers.lt.tools.StringFacs;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author liting
 * @author ($Date: 2012/04/21 05:47:40 $ modification by $Author: administrator $)
 * @version $Revision: 1.4 $ 2014-4-22
 * @since 1.0 hibernate4 改造升级
 */
public class JdbcTemplate {
    private SessionFactory sessionFactory;
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public void save(Object o){
        getCurrentSession().save(o);
    }
    public void delete(Object entity) throws DataAccessException {
        getCurrentSession().delete((Object) entity);
    }
    public void saveOrUpdate(Object o){
        getCurrentSession().saveOrUpdate(o);
    }
    public <T> T get(Class<T> entityClass, Serializable id){
        return (T) getCurrentSession().get(entityClass,id);
    }
    public Session getCurrentSession(){
        Session session;
        try {
            session = this.sessionFactory.getCurrentSession();
        }catch (HibernateException e){
            session = this.sessionFactory.getCurrentSession();
        }
        return session;
    }
    //查询返回一条数据
    public Map queryData(String sql) {
        Map map = new HashMap();
        List<Map> list = getCurrentSession().createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        if (list.size() > 0) {
            map = list.get(0);
        }
        return map;
    }
    //执行原生
    public boolean excuteSql(String sql) throws SQLException {
        SQLQuery sqlQuery = getCurrentSession().createSQLQuery(sql);
        int aBoolean = 0;
        aBoolean = sqlQuery.executeUpdate();
        return aBoolean > 0;
    }

    //查询列表
    public List<Map> queryDatas(String sql) {
        List<Map> list = getCurrentSession().createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return list;
    }

    //查询数据，返回pojo 对像集合
    public <T>List<T> queryEntitys(String sql, Class entity) {
        List<T> list = getCurrentSession().createSQLQuery(sql).addEntity(entity).list();
        return list;
    }

    //分页查询,返回map 集合对象
    public Page pageList(String sql, Page page) {
        //组织分页语句
        PageSql pageSql = new PageSql();
        String ls_Sql = pageSql.getSql(sql, page);
        //取出总数
        List sizeList = getCurrentSession().createSQLQuery(sql).list();
        //查询结果
        //List<Entity> list = session.createSQLQuery(ls_Sql).addEntity(entity).list();
        List<Map> list = getCurrentSession().createSQLQuery(ls_Sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        // Query query  = session.createSQLQuery(ls_Sql).setResultTransformer(Transformers.aliasToBean(entity));
        Page newPage = new Page();
        newPage.setList(list);
        //session.close();
        //把查询出的结果，放到列表中
        newPage.setPagetotal(sizeList.size());
        newPage.setRows(page.getRows());
        newPage.setPage(page.getPage());
        return newPage;
    }

    /***执行hql****/

    /**
     * hql  分页
     * @param hql
     * @param pageNo
     * @param pageSize
     * @param map
     * @param <T>
     * @return
     */
    public <T> List<T> findByPage(String hql, int pageNo, int pageSize, Map map) {
        Query query = getSessionFactory()
                .getCurrentSession().createQuery(hql);
        //判断参数不为空则
        if(!StringFacs.isEmpty(map)) {
            Iterator it = map.keySet().iterator();
            while (it.hasNext()) {
                Object key = it.next();
                query.setParameter(key.toString(), map.get(key));
            }
        }
        return (List<T>) query.setFirstResult((pageNo - 1) * pageSize)
                .setMaxResults(pageSize)
                .list();
    }

    /**
     * @function 根据查询条件查询记录数的个数
     * @param hql
     *            hql查询语句
     * @param map
     *            用map封装查询条件
     * @return 数据库中满足查询条件的数据的条数
     */
    public int getTotalCount(String hql, Map map)
    {
        try
        {
            Query query = getSessionFactory()
                    .getCurrentSession().createQuery(hql);

            if(!StringFacs.isEmpty(map)) {
                Iterator it = map.keySet().iterator();
                while (it.hasNext()) {
                    Object key = it.next();
                    query.setParameter(key.toString(), map.get(key));
                }
            }

            int count = ((Long) query.iterate().next()).intValue();

            // Integer i = (Integer) query.list().get(0);
            //return i;
            return  count;
        } catch (RuntimeException re)
        {
            throw re;
        }
    }
    public void deleteAll(List list) throws DataAccessException {
        for (Object entity : list) {
            getCurrentSession().delete((Object) entity);
        }
    }


}
